package com.bnyy.medicalHousekeeper.activity;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;

import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;

import com.bnyy.common.Constant;
import com.bnyy.common.EasyPhotosGlideEngine;
import com.bnyy.gbp.permission.PermissionHelper;
import com.bnyy.medicalHousekeeper.DialogHelper;
import com.bnyy.medicalHousekeeper.R;
import com.bnyy.medicalHousekeeper.base.BaseActivityImpl;
import com.bnyy.medicalHousekeeper.moudle.message.activity.JoinGroupChatActivity;
import com.bnyy.medicalHousekeeper.moudle.message.activity.UserHomePageActivity;
import com.bnyy.medicalHousekeeper.request.BaseObserverImpl;
import com.bnyy.medicalHousekeeper.request.RequestManager;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.huantansheng.easyphotos.EasyPhotos;
import com.huantansheng.easyphotos.models.album.entity.Photo;

import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bingoogolapple.qrcode.core.QRCodeView;
import cn.bingoogolapple.qrcode.zxing.QRCodeDecoder;
import cn.bingoogolapple.qrcode.zxing.ZXingView;

public class ScanQrcodeActivity extends BaseActivityImpl implements QRCodeView.Delegate {

    @BindView(R.id.cb_light)
    CheckBox cbLight;
    @BindView(R.id.iv_album)
    ImageView ivAlbum;
    @BindView(R.id.zxingview)
    ZXingView zXingView;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    private ActivityResultLauncher<String[]> launcher;
    
    private View.OnClickListener l = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            zXingView.startSpot();
        }
    };

    public static void show(Context context) {
        Intent intent = new Intent(context, ScanQrcodeActivity.class);
        context.startActivity(intent);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_scan_qrcode;
    }

    @Override
    public String getTitleStr() {
        return null;
    }

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        cbLight.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    zXingView.openFlashlight();
                } else {
                    zXingView.closeFlashlight();
                }
            }
        });

        launcher = registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), new ActivityResultCallback<Map<String, Boolean>>() {
            @Override
            public void onActivityResult(Map<String, Boolean> result) {
                result.forEach(new BiConsumer<String, Boolean>() {
                    @Override
                    public void accept(String s, Boolean aBoolean) {
                        switch (s) {
                            case Manifest.permission.CAMERA:
                                if (aBoolean) {
                                    zXingView.setDelegate(ScanQrcodeActivity.this);
                                    zXingView.startSpot();
                                }
                                break;
                        }
                    }
                });
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        zXingView.startCamera(); // 打开后置摄像头开始预览，但是并未开始识别
//        zbarview.startCamera(Camera.CameraInfo.CAMERA_FACING_FRONT); // 打开前置摄像头开始预览，但是并未开始识别
        zXingView.showScanRect();
//        zbarview.startSpotAndShowRect(); // 显示扫描框，并开始识别
        startSpot();
    }

    private void startSpot() {
        PermissionHelper.getInstance().requestPermission(new PermissionHelper.RequestPermission() {
            @Override
            public String[] permissions() {
                return new String[]{
                        Manifest.permission.CAMERA
                };
            }

            @Override
            public void granted(HashSet<String> granted) {
                zXingView.setDelegate(ScanQrcodeActivity.this);
                zXingView.startSpot();
            }

            @Override
            public void denied(HashSet<String> denied) {
                DialogHelper.showTipsDialog(mContext, "获取相机权限失败，请手动打开相机权限",
                        new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                finish();
                            }
                        });
            }
        });
    }

    @Override
    protected void onStop() {
        zXingView.stopCamera(); // 关闭摄像头预览，并且隐藏扫描框
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        zXingView.onDestroy(); // 销毁二维码扫描控件
        super.onDestroy();
    }

    @Override
    public void onScanQRCodeSuccess(String result) {
        Log.e("scan qrcode", "onScanQRCodeSuccess result = " + result);
//        setTitle("扫描结果为：" + result);
//        vibrate();
        dealQrcodeResult(result);
        zXingView.stopSpot(); // 停止识别
        zXingView.getCameraPreview();
    }

    @Override
    public void onCameraAmbientBrightnessChanged(boolean isDark) {
        // 这里是通过修改提示文案来展示环境是否过暗的状态，接入方也可以根据 isDark 的值来实现其他交互效果
        String tipText = zXingView.getScanBoxView().getTipText();
        String ambientBrightnessTip = "\n环境过暗，请打开闪光灯";
        if (isDark) {
            if (!tipText.contains(ambientBrightnessTip)) {
                zXingView.getScanBoxView().setTipText(tipText + ambientBrightnessTip);
            }
        } else {
            if (tipText.contains(ambientBrightnessTip)) {
                tipText = tipText.substring(0, tipText.indexOf(ambientBrightnessTip));
                zXingView.getScanBoxView().setTipText(tipText);
            }
        }
    }

    @Override
    public void onScanQRCodeOpenCameraError() {
        DialogHelper.showTipsDialog(mContext, "提示", "打开相机出错", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    ProgressDialog progressDialog;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == Constant.ActivityRequestCode.GET_QRCODE && data != null) {
            ArrayList<Photo> resultPhotos = data.getParcelableArrayListExtra(EasyPhotos.RESULT_PHOTOS);
            if (resultPhotos != null && resultPhotos.size() > 0) {
                String s = resultPhotos.get(0).path;

                Log.e("path", s);

                new AsyncTask<Void, Void, String>() {
                    @Override
                    protected String doInBackground(Void... params) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                progressDialog = ProgressDialog.show(mContext, "", "正在解析二维码，请稍后...");
                            }
                        });
                        return QRCodeDecoder.syncDecodeQRCode(s);
                    }

                    @Override
                    protected void onPostExecute(String result) {
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        dealQrcodeResult(result);
                    }
                }.execute();
            }
        }
    }

    private void dealQrcodeResult(String result) {
        if (TextUtils.isEmpty(result)) {
            DialogHelper.showTipsDialog(mContext, "扫码提示", "识别二维码失败，请重试", l);
        } else {
            Log.e("onPostExecute", "result = " + result);

            if (result.contains("https://www.bainianyang.com/html/h5/#/appdownload3")
                    && result.contains("share_code=")) {
                String[] split = result.split("\\?");
                if (split.length > 1) {
                    Map<String, String> collect = Arrays.stream(split[1].split("&"))
                            .map(new Function<String, Map.Entry<String, String>>() {
                                @Override
                                public Map.Entry<String, String> apply(String s) {
                                    String[] split = s.split("=");
                                    return new AbstractMap.SimpleEntry<>(split[0], split[1]);
                                }
                            })
                            .collect(Collectors.toMap(new Function<Map.Entry<String, String>, String>() {
                                @Override
                                public String apply(Map.Entry<String, String> entry) {
                                    return entry.getKey();
                                }
                            }, new Function<Map.Entry<String, String>, String>() {
                                @Override
                                public String apply(Map.Entry<String, String> entry) {
                                    return entry.getValue();
                                }
                            }));


                    String shareCode = collect.get("share_code");
                    if (!TextUtils.isEmpty(shareCode)) {

                        HashMap<String, Object> params = new HashMap<>();
                        params.put("share_code", shareCode);
                        requestManager.request(requestManager.mJavaRetrofitService.decodeShareData(RequestManager.getJsonRequestBody(params))
                                , new BaseObserverImpl<Object>(mContext) {
                                    @Override
                                    public void onSuccess(Object o) {
                                        super.onSuccess(o);

                                        String json = new Gson().toJson(o);
                                        JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();
                                        Set<Map.Entry<String, JsonElement>> entries = jsonObject.entrySet();

                                        String type = collect.get("type");
                                        if (!TextUtils.isEmpty(type)) {
                                            if (type.equals("1")) {
//                                                if (jsonObject.has("group_id")) {
////                                                    JoinGroupChatActivity.show(mContext, jsonObject.get("group_id").getAsInt());
////                                                    finish();
////                                                }
                                                Optional<Integer> groupId = entries.stream()
                                                        .filter(entry -> entry.getKey().equals("group_id"))
                                                        .map(entry -> entry.getValue().getAsInt())
                                                        .findFirst();

                                                groupId.ifPresent(new Consumer<Integer>() {
                                                    @Override
                                                    public void accept(Integer integer) {
                                                        JoinGroupChatActivity.show(mContext, integer);
                                                        finish();
                                                    }
                                                });
                                            } else {
                                                if (jsonObject.has("user_id") && jsonObject.has("role_id")) {
                                                    UserHomePageActivity.show(mContext, jsonObject.get("user_id").getAsInt(), jsonObject.get("role_id").getAsInt());
                                                    finish();
                                                }
                                            }
                                        }
                                    }

                                    @Override
                                    public void onOtherCode(int code) {
                                        super.onOtherCode(code);
                                        zXingView.startSpot();
                                    }

                                    @Override
                                    public void onError(Throwable e) {
                                        super.onError(e);
                                        zXingView.startSpot();
                                    }
                                });
                    }
                }
            }
        }
    }

    @OnClick({R.id.iv_album, R.id.iv_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_album:
                EasyPhotos.createAlbum(mContext, false, false, EasyPhotosGlideEngine.getInstance())//参数说明：上下文，是否显示相机按钮，是否使用宽高数据（false时宽高数据为0，扫描速度更快），[配置Glide为图片加载引擎](https://github.com/HuanTanSheng/EasyPhotos/wiki/12-%E9%85%8D%E7%BD%AEImageEngine%EF%BC%8C%E6%94%AF%E6%8C%81%E6%89%80%E6%9C%89%E5%9B%BE%E7%89%87%E5%8A%A0%E8%BD%BD%E5%BA%93)
                        .setPuzzleMenu(false)
                        .setCount(1)//参数说明：最大可选数，默认1
                        .start(Constant.ActivityRequestCode.GET_QRCODE);
                break;
            case R.id.iv_back:
                finish();
                break;
        }
    }
}




























